package com.zws.cucumber.snapshot;

import com.zws.cucumber.util.cass.ZwsCassTemplateImpl;
import com.zws.cucumber.util.cass.backdoor.ZwsCassBackdoorClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class ZwsRemoteCassSnapshotManager implements ZwsSnapshotManager<Map<String, Object>> {

    private static Logger logger = LoggerFactory.getLogger(ZwsRemoteCassSnapshotManager.class);

    private ZwsCassBackdoorClient cassBackdoorClient;

    private ConcurrentMap<String, Map<String, Object>> snapshots = new ConcurrentHashMap<>();

    public ZwsRemoteCassSnapshotManager(ZwsCassBackdoorClient cassBackdoorClient) {
        this.cassBackdoorClient = cassBackdoorClient;
    }

    @Override
    public String name() {
        return "remote cassandra";
    }

    @Override
    public ConcurrentMap<String, Map<String, Object>> snapshots() {
        return snapshots;
    }

    @Override
    public void snapshot0(String snapshotName, Map<String, Object> args) {
        Map<String, Object> snapshot = new HashMap<>();
        put(snapshotName, snapshot);
        snapshot.put("modifiedTables", ZwsCassTemplateImpl.getModifiedTables());

        cassBackdoorClient.takeSnapshot(snapshotName, System.getProperty("zws.cassandra.keySpace"));
    }

    @Override
    public void restore0(String snapshotName, Map<String, Object> args) {
        Map<String, Object> snapshot = get(snapshotName);
        ZwsCassTemplateImpl.putAllModifiedTables((Map<String, String>) snapshot.get("modifiedTables"));

        cassBackdoorClient.restoreSnapshot(snapshotName, System.getProperty("zws.cassandra.keySpace"));
    }

    @Override
    public Logger logger() {
        return logger;
    }

    @Override
    public void delete(String snapshotName) {
        ZwsSnapshotManager.super.delete(snapshotName);
        cassBackdoorClient.deleteSnapshot(snapshotName);
    }

    @Override
    public void clear() {
        ZwsSnapshotManager.super.clear();
        cassBackdoorClient.clearSnapshots();
    }

}
